<template>
  <div class="production-plan">
    <el-button type="success" @click="addjihau" class="save-button">保存主表单和明细</el-button>
    <h3 class="title"> 包装成品质检</h3>

    <!-- 基本信息 -->
    <el-form ref="formRef" :model="formData" :rules="rules" label-position="right" label-width="120px"
             class="form-container">
      <el-row :gutter="30">
        <!-- 第一行 -->
        <el-col :span="8">
          <el-form-item label="生产批号">
            <el-input
              placeholder="请输入"
              v-model="formData.batchNumber"
              required
            >
              <template #suffix>
                <el-button size="mini" @click="openAssociatedItemDialog1">
                  <i class="el-icon-search"></i>
                </el-button>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="生产时间" prop="productionDate" style="margin-bottom: 20px;">
            <el-date-picker
              v-model="formData.productionDate"
              type="date"
              required
              placeholder="请选择事务起始时间"
              style="width: 100%;"
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="包装类型">
            <el-select v-model="formData.packagingType" placeholder="选择包装类型">
              <el-option label="瓶装" value="瓶装"/>
              <el-option label="灌装" value="灌装"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="包装标签质量">
            <el-select v-model="formData.labelQuality" placeholder="选择包装标签质量"> <!-- 修改了 placeholder -->
              <el-option label="好" value="好"/>
              <el-option label="一般" value="一般"/>
              <el-option label="差" value="差"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="包装密封情况">
            <el-select v-model="formData.capSealing" placeholder="选择包装密封情况">
              <el-option label="密封" value="密封"/>
              <el-option label="松动" value="松动"/>
              <el-option label="泄漏" value="泄漏"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="包装状况">
            <el-select v-model="formData.bottleCondition" placeholder="选择包装状况">
              <el-option label="完好" value="完好"/>
              <el-option label="破裂" value="破裂"/>
              <el-option label="有划痕" value="有划痕"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="灌装液位">
            <el-select v-model="formData.fillLevel" placeholder="选择灌装液位">
              <el-option label="合格" value="合格"/>
              <el-option label="不合格" value="不合格"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="包装材料柔韧性">
            <el-select v-model="formData.flexibility" placeholder="选择包装材料柔韧性">
              <el-option label="合格" value="合格"/>
              <el-option label="不合格" value="不合格"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="包装材料耐水性">
            <el-select v-model="formData.waterResistance" placeholder="选择包装材料耐水性">
              <el-option label="合格" value="合格"/>
              <el-option label="不合格" value="不合格"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="包装材料透气性">
            <el-select v-model="formData.breathability" placeholder="选择包装材料透气性">
              <el-option label="合格" value="合格"/>
              <el-option label="不合格" value="不合格"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="包装表面平整度">
            <el-select v-model="formData.surfaceFlatness" placeholder="选择包装表面平整度">
              <el-option label="合格" value="合格"/>
              <el-option label="不合格" value="不合格"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="包装颜色一致性">
            <el-select v-model="formData.colorConsistency" placeholder="选择包装颜色一致性">
              <el-option label="合格" value="合格"/>
              <el-option label="不合格" value="不合格"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="质检日期" prop="inspectionDate" style="margin-bottom: 20px;">
            <el-date-picker
              v-model="formData.inspectionDate"
              type="date"
              required
              placeholder="请选择质检日期"
              style="width: 100%;"
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="质检人员姓名" style="margin-bottom: 20px;">
            <el-input v-model="formData.inspectorName" placeholder="请输入质检人员姓名"/> <!-- 修改了 placeholder -->
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="质检结果">
            <el-select v-model="formData.inspectionResult" placeholder="选择质检结果"> <!-- 修改了 placeholder -->
              <el-option label="通过" value="true"/> <!-- 修改了 label 使其更易读 -->
              <el-option label="不通过" value="false"/> <!-- 修改了 label 使其更易读 -->
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="备注信息" style="margin-bottom: 20px;">
            <el-input v-model="formData.remarks" placeholder="请输入" type="textarea" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-dialog
      v-model="associatedItemDialogVisible1"
      width="500px"
      title="生产批次信息选择"
      append-to-body
    >
      <el-table
        :data="associatedItems1"
        highlight-current-row
        border
        size="small"
        @current-change="handleAssociatedItemChange1"
      >
        <el-table-column type="index" label="序号" />
        <el-table-column property="productName" label="产品名称" />
        <el-table-column property="lotNumber" label="生产批次" />
        <el-table-column property="specification" label="包装规格" />
        <el-table-column property="plannedQuantity" label="计划包装数量" />
        <el-table-column property="actualQuantity" label="实际包装数量" />
        <el-table-column property="startDate" label="包装开始日期" />
        <el-table-column property="endDate" label="包装结束日期" />
        <el-table-column property="packingCrews" label="包装班组" />
        <el-table-column property="materialName" label="包装材料名称" />
        <el-table-column property="model" label="规格型号" />
        <el-table-column property="unit" label="单位" />
        <el-table-column property="planUsage" label="计划用量" />
        <el-table-column property="actualUsage" label="实际用量" />
        <el-table-column property="consumption" label="损耗量" />
        <el-table-column property="wearRate" label="损耗率" />
        <el-table-column property="equipmentName" label="设备名称" />
        <el-table-column property="equipmentNumbering" label="设备编号" />
        <el-table-column property="duration" label="运行时长" />
        <el-table-column property="frequency" label="故障次数" />
        <el-table-column property="cause" label="故障原因" />
        <el-table-column property="measures" label="故障处理措施" />
        <el-table-column property="inspectionItems" label="检验项目" />
        <el-table-column property="inspectionStandards" label="检验标准" />
        <el-table-column property="testResults" label="检验结果" />
        <el-table-column property="unqualifiedNum" label="不合格数量" />
        <el-table-column property="unqualifiedCause" label="不合格原因" />
        <el-table-column property="unqualifiedMeasure" label="处理措施" />
      </el-table>
      <template #footer>
        <el-button @click="pickAssociatedItem1">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>
  
  <script setup>
  import { ref, reactive, onMounted, watch } from 'vue';
  import { ElMessage, ElMessageBox } from 'element-plus';
  import { useRouter, useRoute } from 'vue-router';
  import { Materialread, Materialwrite } from '@/axios/axiosHelper';
  import axios from 'axios';
  import { th } from 'element-plus/es/locales.mjs';
  
  const formRef = ref(null);
  const currentUser = ref("admin");
  const router = useRouter();
  const route = useRoute();
  
  // 主表单数据
  const formData = reactive({
    id: route.params.id,
  "batchNumber": "",
  "productionDate": "",
  "packagingType": "",
  "labelQuality": "",
  "capSealing": "",
  "bottleCondition": "",
  "fillLevel": "",
  "flexibility": "",
  "waterResistance": "",
  "breathability": "",
  "surfaceFlatness": "",
  "colorConsistency": "",
  "inspectionDate": new Date().toISOString(),
  "inspectorName": currentUser.value,
  "inspectionResult": true,
  "remarks": "",
  "isDel": true,
  "request": "" // 补充此字段
  });
  
  // 主表单验证规则
  const rules = reactive({
    bomSubject: [
      { required: true, message: '不能为空', trigger: 'blur' }
    ],
    productName: [
      { required: true, message: '不能为空', trigger: 'blur' }
    ],
    documentNo: [
      { required: true, message: '不能为空', trigger: 'blur' }
    ],
  });
  
  
  
  const getProductionById = (id) => {
  console.log('查看反填数据:', id);
  Materialread.get('p-read/api/CompletedStorage/FTPackagingQuality', {
      params:{
        id: route.query.id
      }
    })
    .then(res=>{
      formData.id = res.data.data[0].id;
      formData.batchNumber = res.data.data[0].batchNumber;
      formData.productionDate = res.data.data[0].productionDate;
      formData.packagingType = res.data.data[0].packagingType;
      formData.labelQuality = res.data.data[0].labelQuality;
      formData.capSealing = res.data.data[0].capSealing;
      formData.bottleCondition = res.data.data[0].bottleCondition;
      formData.fillLevel = res.data.data[0].fillLevel;
      formData.flexibility = res.data.data[0].flexibility;
      formData.waterResistance = res.data.data[0].waterResistance;
      formData.breathability = res.data.data[0].breathability;
      formData.surfaceFlatness = res.data.data[0].surfaceFlatness;
      formData.colorConsistency = res.data.data[0].colorConsistency;
      formData.inspectionDate = res.data.data[0].inspectionDate;
      formData.inspectorName = res.data.data[0].inspectorName;
      formData.inspectionResult = res.data.data[0].inspectionResult;
      formData.remarks = res.data.data[0].remarks;
      formData.modelValue = res.data.data[0];
      console.log('包装质检反填数据:', res.data);
    })
  };
  
  // 明细数据列表
  const planDetailsList = ref([]);
  const attachments = ref([]);
  
  // // 保存主表单
   const addjihau = () => {
    Materialwrite.post('p-write/api/PackagingQuality/Handle', formData)
      .then(response => {
       if (response.data.code === 200) {
         ElMessage.success('完工质检修改成功');
         console.log(response.data.data);
         router.push("/GetPackagingQuality");
      } else {
         ElMessage.error(`完工质检修改失败：${response.data.message}`);
      }
      })
  };
  
  onMounted(()=>{
    getProductionById();
  })
  
  
  onMounted(() => {
  // 检查函数是否存在
  if (typeof fetchAssociatedProjects === 'function') {
    fetchAssociatedProjects();
  }
  if (typeof fetchAssociatedProjects1 === 'function') {
    fetchAssociatedProjects1();
  }
});

// 对话框显示状态
const associatedItemDialogVisible1 = ref(false);
const currentAssociatedItem1 = ref({});
// 关联项目数据
const associatedItems1 = ref([]);
// 打开关联项目选择对话框
const openAssociatedItemDialog1 = () => {
  associatedItemDialogVisible1.value = true;
};
// 当前选中的关联项目行
const handleAssociatedItemChange1 = (val) => {
  currentAssociatedItem1.value = val;
};
// 选择关联项目
const pickAssociatedItem1 = () => {
  if (currentAssociatedItem1.value) {
    formData.batchNumber = currentAssociatedItem1.value.lotNumber;
    // 确保 formData 中存在这些属性
    // formData.product_model 不存在于 formData 中，可根据实际情况处理或移除
    // formData.production_batch 不存在于 formData 中，可根据实际情况处理或移除
    // formData.production_date 不存在于 formData 中，可根据实际情况处理或移除
    associatedItemDialogVisible1.value = false;
  }
};
// 获取关联项目数据
const fetchAssociatedProjects1 = () => {
  axios.get("http://localhost:5118/api/Monitor/GetMonito")
   .then(res => {
      associatedItems1.value = res.data.data;
    })
   .catch(error => {
      console.error('获取关联项目数据出错:', error);
      ElMessage.error('获取关联项目数据时出现错误，请检查网络或重试');
    });
};
  
  </script>
  
  <style scoped>
  .production-plan {
    padding: 30px;
    background-color: #f0f2f5;
    border-radius: 10px;
    box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
    font-family: 'Arial', sans-serif;
  }
  
  .title {
    text-align: center;
    margin-bottom: 30px;
    color: #2c3e50;
    font-size: 24px;
    font-weight: 600;
  }
  
  .save-button {
    display: block;
    margin: 0 auto 30px;
    padding: 12px 24px;
    font-size: 16px;
    border-radius: 6px;
  }
  
  .form-container {
    background-color: white;
    padding: 30px;
    border-radius: 10px;
    box-shadow: 0 4px 10px rgba(0, 0, 0, 0.05);
  }
  
  .el-form-item__label {
    color: #34495e;
    font-size: 16px;
    font-weight: 500;
  }
  
  .el-input,
  .el-input-number,
  .el-date-picker {
    border-radius: 6px;
    border: 1px solid #ccc;
    padding: 10px;
    font-size: 14px;
  }
  
  .el-input:focus,
  .el-input-number:focus,
  .el-date-picker:focus {
    border-color: #42b983;
    outline: none;
    box-shadow: 0 0 5px rgba(66, 185, 131, 0.2);
  }
  
  </style>